import kiwiIntl from 'kiwi-intl';
import storage, { CURRENT_LANG } from '@/utils/storage';
import enUsLangs from './langs/en-US';
import zhCNLangs from './langs/zh-CN';
import type { IAPI } from './typing';
import { LangEnum } from './typing';

export type Langs = typeof zhCNLangs & IAPI;

export const langs = {
  [LangEnum.zhCN]: zhCNLangs,
  [LangEnum.enUS]: enUsLangs,
};

// 初始化
const I18N = kiwiIntl.init(LangEnum.enUS, langs) as any as Langs;
I18N.currentLang = LangEnum.zhCN;

// 重写setLang
I18N.setLangHandle = (lang: LangEnum) => {
  I18N.currentLang = lang;
  I18N.setLang(lang);

  storage.setStorage(CURRENT_LANG, I18N.currentLang);
};

// 根据用户上次选择语言重置
const lastLang = storage.getStorage(CURRENT_LANG) as LangEnum;
if (lastLang) {
  I18N.setLangHandle(lastLang);
} else {
  storage.setStorage(CURRENT_LANG, I18N.currentLang);
}

export default I18N;
